package com.qf.aliyun.oss;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.qf.aliyun.MyAliSecrets;

import java.io.File;

public class AliyunOssUtils {

    public static void main(String[] args) throws Exception {
        String filePath= "D:\\pic\\2.gif";
        String objectName = "pic/2.gif";
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "fmall2305001";
        uploadFile(endpoint,bucketName,filePath,objectName);
    }

    private static void uploadFile(String endpoint,String bucketName,String filePath,String objectName) throws com.aliyuncs.exceptions.ClientException {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, MyAliSecrets.accessKeyId, MyAliSecrets.accessKeySecret);

        try {
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));

            // 上传文件。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            System.out.println(result);
            System.out.println(result.getETag());
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}